package example2;


import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;


public class App {


    public static void main(String[] args) {
        User user = new User();
        user.setAddress("BeiJing");
        user.setAge(60);
        user.setName("lll");
        String sql = query(user);
        System.out.println(sql);
    }


    public static String query(User user) {
        StringBuilder sql = new StringBuilder();
        Class clazz = user.getClass();

        if (clazz.isAnnotationPresent(Table.class)) {
            Table annotation = (Table) clazz.getAnnotation(Table.class);
            sql.append(" SELECT * FROM ");
            sql.append(annotation.value());
            sql.append(" WHERE 1 = 1 ");
        }

        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            if (field.isAnnotationPresent(Column.class)) {
                String columnName = field.getAnnotation(Column.class).value();
                Object columnValue = null;
                try {
                    PropertyDescriptor descriptor = new PropertyDescriptor(field.getName(), clazz);
                    columnValue = descriptor.getReadMethod().invoke(user);

                    if (columnValue != null) {
                        if (columnValue instanceof String) {
                            columnValue = "\"" + columnValue + "\"";
                        }
                        sql.append(" AND " + columnName + " = " + columnValue);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return sql.toString();
    }

}



